/// <reference types="node" />
(async () => {
  const fs = require("fs");
  const process = require("process");
  const readline = require("readline");
  const toml = require("@iarna/toml");
  const wrangler2 = require("./wrangler2");

  /**
   * @param {readline.Interface} interface0
   * @param {string} query
   * @returns {Promise<string>}
   */
  function input(interface0, query) {
    return new Promise((resolve) => interface0.question(query, resolve));
  }

  /**
   * @param {string} name
   * @param {boolean} preview
   * @param {ReturnType<wrangler2.listKVNamespaces>} namespaces
   * @returns {string}
   */
  function withKVNamespace(name, preview, namespaces) {
    const namespace = namespaces[wrangler2.title(name, preview)];
    if (namespace !== undefined) {
      return namespace.id;
    }
    return wrangler2.createKVNamespace(name, preview);
  }

  if (fs.existsSync("wrangler.toml")) {
    console.log("Config exists.");
    process.exit();
  }

  if (!wrangler2.authenticated()) {
    console.log("You are not authenticated.");
    wrangler2.login();
  }
  console.log("Logged in.");
  console.log();

  const interface0 = readline.createInterface(process.stdin, process.stdout);
  const baseDomain = await input(interface0, "Base domain: ");
  const domain = `${wrangler2.config.name}.${baseDomain}`;

  const namespaces = wrangler2.listKVNamespaces();
  const kvNamespaceId = withKVNamespace("kv", false, namespaces);
  const kvPreviewNamespaceId = withKVNamespace("kv", true, namespaces);

  const config = {
    name: wrangler2.config.name,
    main: "src/index.ts",
    compatibility_date: "2022-09-08",
    routes: [{ pattern: domain, custom_domain: true }],
    kv_namespaces: [
      { binding: "KV", id: kvNamespaceId, preview_id: kvPreviewNamespaceId },
    ],
  };

  fs.writeFileSync("wrangler.toml", toml.stringify(config));
  process.exit();
})();
